package com.ipan.builder.freemarker;

import com.ipan.builder.ognl.ValueStack;

import freemarker.template.ObjectWrapper;
import freemarker.template.SimpleHash;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

/**
 * OGNL数据模型
 * 
 * @author iPan
 * @version 2013-11-30
 */
public class OgnlHashModel extends SimpleHash {
	private static final long serialVersionUID = 8785375848762095829L;
	private ValueStack stack;

	public OgnlHashModel(ObjectWrapper objectWrapper, ValueStack stack) {
		super(objectWrapper);
		this.stack = stack;
	}

	public OgnlHashModel(ObjectWrapper objectWrapper) {
		super(objectWrapper);
	}

	public TemplateModel get(String key) throws TemplateModelException {
		// Lookup in default scope
		TemplateModel model = super.get(key);
		if (model != null) {
			return model;
		}

		if (stack != null) {
			Object obj = stack.findValue(key);

			if (obj != null) {
				return wrap(obj);
			}

			// ok, then try the context
			obj = stack.getContext().get(key);
			if (obj != null) {
				return wrap(obj);
			}
		}

		return null;
	}
}
